//
//  PrivateChatViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/29.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PrivateChatViewController.h"

@interface PrivateChatViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *chatContentArr;
@property (nonatomic, strong) NSDictionary *userInfo;


@end

@implementation PrivateChatViewController {
    UITableView         *_tableView;
    UITextField         *_privateChatTextF; // 私聊输入框
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cNotification" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(c2cNotification:)name:@"c2cNotification" object:nil];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-40-64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    _privateChatTextF= [[UITextField alloc] initWithFrame:CGRectMake(5, SCREEN_HEIGHT-40-64+2, SCREEN_WIDTH-10, 36)];
    [self.view addSubview:_privateChatTextF];
    _privateChatTextF.returnKeyType = UIReturnKeySend;
    _privateChatTextF.backgroundColor = UISeparatedColorRGB;
    _privateChatTextF.delegate = self;
    _privateChatTextF.layer.cornerRadius = 2;
    _privateChatTextF.layer.masksToBounds = YES;
    
}


- (void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [super viewWillAppear:animated];
    /**
     *  如果状态栏背景为浅色，应选用黑色字样式(UIStatusBarStyleDefault，默认值),如果背景为深色，则选用白色字样式(UIStatusBarStyleLightContent)。
     UIApplication 一个APP只有一个，你在这里可以设置应用级别的设置，就像上面的实例一样，详细见http://www.cnblogs.com/wendingding/p/3766347.html
     */
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    
    [self getlist];
}

- (void)getlist {
    
//    [self.chatMessageVC.data removeAllObjects];
//    [self.chatMessageVC.tableView reloadData];
    
    _msgHandler = [[AVIMMsgHandler alloc] init];
    
    [self getConversation:self.currConversation];
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell2"];
    }
    else{
        for (UIView *cellView in cell.subviews){
            [cellView removeFromSuperview];
        }
    }
    
    NSArray *arr = self.chatContentArr[indexPath.row];
    NSDictionary *dict = arr[1];
    
    //创建头像
    UIImageView *photo ;
    // 当前用户的
    if ([dict[@"uid"] isEqualToString:[GetUserDefaule(USERINFO) valueForKey:@"user_id"]]) {
        photo = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60, 10, 50, 50)];
        photo.layer.cornerRadius = 25;
        photo.layer.masksToBounds = YES;
        [cell addSubview:photo];
        [photo sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
        
        // 解析内容            // 文本
        [cell addSubview:[self bubbleView:arr[0] from:YES withPosition:65]];
    }else{
        photo = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
        photo.layer.cornerRadius = 25;
        photo.layer.masksToBounds = YES;
        [cell addSubview:photo];
        [photo sd_setImageWithURL:[NSURL URLWithString:[[dict valueForKey:@"user_info"] valueForKey:@"face"]] placeholderImage:[UIImage imageNamed:@"placeHlder.png"]];
        
        [photo sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
        
        // 解析内容
        [cell addSubview:[self bubbleView:arr[0] from:NO withPosition:65]];
        
    }
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.chatContentArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *arr = self.chatContentArr[indexPath.row];
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size;
    size = [arr[0] sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    return size.height+44;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    
}

//泡泡文本
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    //    NSLog(@"%f,%f",size.width,size.height);
    
    
    //添加文本信息
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f, 20.0f, size.width+10, size.height+10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    //    bubbleText.text = text;
    //    bubbleText.text = [EaseConvertToCommonEmoticonsHelper convertToSystemEmoticons:text];
    bubbleText.text = text;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCREEN_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}


- (void)getConversation:(TIMConversation *)conversation {
    
    [self.chatContentArr removeAllObjects];
    
    [conversation getMessage:10 last:nil succ:^(NSArray *msgs) {
        for (TIMMessage *msg in msgs) {
            NSMutableArray *listArr = [[NSMutableArray alloc] init];
            for(int index = 0; index < [msg elemCount]; index++) {
                TIMElem *elem = [msg getElem:index];
                if([elem isKindOfClass:[TIMTextElem class]]) {
                    // 消息总入口频率限制
                    static TCFrequeControl *freqControl = nil;
                    if (freqControl == nil) {
                        freqControl = [[TCFrequeControl alloc] initWithCounts:20 andSeconds:1];
                    }
                    if (![freqControl canTrigger]) {
                        return;
                    }
                    // 文本消息
                    TIMTextElem *textElem = (TIMTextElem *)elem;
                    NSString *msgText = textElem.text;
                    NSDictionary* dict = [TCUtil jsonData2Dictionary:msgText];
                    NSLog(@"获取聊天信息 = %@", dict);
                    if (dict == nil) {
                        return;
                    }
                    NSError *err;
                    NSData *jsonData = [[dict valueForKey:@"senderInfo"] dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                             options:NSJSONReadingMutableContainers
                                                                               error:&err];
                    
                    NSString *currId = [GetUserDefaule(USERINFO) valueForKey:@"user_id"];
                    
                    if ([currId isEqualToString:infoDict[@"uid"]]) {
                        _receiveInfo = dict[@"receiverInfo"];
                        _senderInfo = dict[@"senderInfo"];
                    }
                    else {
                        _receiveInfo = dict[@"senderInfo"];
                        _senderInfo = dict[@"receiverInfo"];
                    }
                    [listArr addObject:dict[@"msg"]];
                    [listArr addObject:infoDict];
                    
                    [self.chatContentArr addObject:listArr];
                    
                }
                else if([elem isKindOfClass:[TIMCustomElem class]]) {
                    // 自定义消息
                    TIMCustomElem* cele = (TIMCustomElem*)elem;
                    NSString *dataStr = [[NSString alloc] initWithData:cele.data encoding:NSUTF8StringEncoding];
                    DebugLog(@"datastr is:%@", dataStr);
                }
            }
        }
        // 数组倒序
        self.chatContentArr = (NSMutableArray *)[[self.chatContentArr reverseObjectEnumerator] allObjects];
        
//        [self reloadTableView];
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"MMMMMMMMMMMM%d, %@", code, msg);
    }];
    
}
//- (void)reloadTableView {
//    
//    for (int i = 0; i < self.chatContentArr.count; i++) {
//        
//        NSString *text = self.chatContentArr[i][0];
//        NSDictionary *userInfo = self.chatContentArr[i][1];
//        
//        ZXMessageModel *message = [[ZXMessageModel alloc] init];
//        message.messageType = ZXMessageTypeText;
//        message.date = [NSDate date];// 当前时间
//        message.text = text;
//        message.imagePath = userInfo[@"headpic"];
//        //        message.from = message.from;
//        
//        if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userInfo[@"imId"]]) {
//            message.ownerTyper = ZXMessageOwnerTypeSelf;
//        }
//        else
//            message.ownerTyper = ZXMessageOwnerTypeOther;
//        
//        [self.chatMessageVC addNewMessage:message];
//        
//    }
//    
//}

- (void)c2cNotification:(NSNotification *)notification {
    NSLog(@"--接收到私聊提醒通知--\n%@", notification.userInfo);
    
    [self getlist];
    
}
- (NSMutableArray *)chatContentArr {
    if (_chatContentArr == nil) {
        _chatContentArr = [[NSMutableArray alloc] init];
    }
    return _chatContentArr;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
